<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{MerchantRechargeRecord, Merchant, MerchantFundFlow};
use think\facade\{Db, Log};
use think\Request;

class MerchantRechargeController extends BaseController
{
    /**
     * 获取充值记录列表
     */
    public function index(Request $request)
    {
        $where = [];
        
        // 商家ID筛选
        if ($merchant_id = $request->param('merchant_id')) {
            $where[] = ['merchant_id', '=', $merchant_id];
        }
        
        // 状态筛选
        if ($status = $request->param('status')) {
            $where[] = ['status', '=', $status];
        }
        
        // 时间范围筛选
        if ($start_time = $request->param('start_time')) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if ($end_time = $request->param('end_time')) {
            $where[] = ['create_time', '<=', $end_time];
        }
        
        // 分页查询
        $page = (int)$request->param('page', 1);
        $limit = (int)$request->param('limit', 15);
        
        $list = MerchantRechargeRecord::with(['merchant'])
            ->where($where)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 审核充值申请
     */
    public function audit(Request $request)
    {
        $data = $this->validate($request->post(), [
            'id' => 'require|integer',
            'status' => 'require|in:2,3', // 2已充值 3已取消
            'remark' => 'max:200'
        ]);
        
        Db::startTrans();
        try {
            $record = MerchantRechargeRecord::where([
                'id' => $data['id'],
                'status' => 0 // 未支付
            ])->find();
            
            if (!$record) {
                throw new \Exception('充值记录不存在或状态已变更');
            }
            
            // 更新充值记录状态
            $record->save([
                'status' => $data['status'],
                'admin_id' => $request->adminId,
                'remark' => $data['remark'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 如果审核通过,增加商家余额
            if ($data['status'] == 2) {
                $merchant = Merchant::find($record->merchant_id);
                if (!$merchant) {
                    throw new \Exception('商家不存在');
                }
                
                // 增加余额
                $merchant->inc('balance', $record->recharge_amount)->update();
                
                // 记录资金流水
                MerchantFundFlow::create([
                    'merchant_id' => $record->merchant_id,
                    'fund_flow_type' => 1, // 充值
                    'fund_flow_amount' => $record->recharge_amount,
                    'fund_flow_time' => date('Y-m-d H:i:s'),
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
            
            Db::commit();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('审核充值申请失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取充值金额配置
     */
    public function amounts()
    {
        $list = [
            ['amount' => 100, 'sort' => 1],
            ['amount' => 200, 'sort' => 2],
            ['amount' => 500, 'sort' => 3],
            ['amount' => 1000, 'sort' => 4],
            ['amount' => 2000, 'sort' => 5],
            ['amount' => 5000, 'sort' => 6]
        ];
        
        return $this->success('获取成功', $list);
    }
    
    /**
     * 更新充值金额配置
     */
    public function updateAmounts(Request $request)
    {
        $data = $this->validate($request->post(), [
            'amounts' => 'require|array'
        ]);
        
        try {
            // 验证金额配置
            foreach ($data['amounts'] as $item) {
                if (!isset($item['amount']) || !isset($item['sort'])) {
                    throw new \Exception('金额配置格式错误');
                }
                if ($item['amount'] <= 0) {
                    throw new \Exception('充值金额必须大于0');
                }
            }
            
            // 更新配置
            $config = [
                'group_name' => 'recharge',
                'config_key' => 'amounts',
                'config_value' => json_encode($data['amounts']),
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            Db::name('platform_config')->where([
                'group_name' => 'recharge',
                'config_key' => 'amounts'
            ])->update($config);
            
            return $this->success('更新成功');
        } catch (\Exception $e) {
            Log::error('更新充值金额配置失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 充值统计
     */
    public function statistics(Request $request)
    {
        try {
            $where = [];
            
            // 时间范围筛选
            if ($start_time = $request->param('start_time')) {
                $where[] = ['create_time', '>=', $start_time];
            }
            if ($end_time = $request->param('end_time')) {
                $where[] = ['create_time', '<=', $end_time];
            }
            
            // 商家筛选
            if ($merchant_id = $request->param('merchant_id')) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }

            // 基础统计
            $stats = MerchantRechargeRecord::where($where)
                ->where('status', 2) // 已充值
                ->field([
                    'count(*) as total_count',
                    'sum(recharge_amount) as total_amount',
                    'avg(recharge_amount) as avg_amount',
                    'max(recharge_amount) as max_amount',
                    'min(recharge_amount) as min_amount'
                ])
                ->find();
                
            // 按日期统计
            $daily = MerchantRechargeRecord::where($where)
                ->where('status', 2)
                ->field([
                    'DATE(create_time) as date',
                    'count(*) as count',
                    'sum(recharge_amount) as amount'
                ])
                ->group('date')
                ->order('date', 'desc')
                ->select();
                
            // 按商家统计TOP10
            $merchants = MerchantRechargeRecord::where($where)
                ->where('status', 2)
                ->with(['merchant'])
                ->field([
                    'merchant_id',
                    'count(*) as count',
                    'sum(recharge_amount) as amount'
                ])
                ->group('merchant_id')
                ->order('amount', 'desc')
                ->limit(10)
                ->select();
                
            return $this->success('获取成功', [
                'stats' => $stats,
                'daily' => $daily,
                'merchants' => $merchants
            ]);
        } catch (\Exception $e) {
            Log::error('获取充值统计失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 导出充值记录
     */
    public function export(Request $request)
    {
        try {
            $where = [];
            
            // 时间范围筛选
            if ($start_time = $request->param('start_time')) {
                $where[] = ['create_time', '>=', $start_time];
            }
            if ($end_time = $request->param('end_time')) {
                $where[] = ['create_time', '<=', $end_time];
            }
            
            // 商家筛选
            if ($merchant_id = $request->param('merchant_id')) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }
            
            // 状态筛选
            if ($status = $request->param('status')) {
                $where[] = ['status', '=', $status];
            }

            $list = MerchantRechargeRecord::with(['merchant'])
                ->where($where)
                ->order('id', 'desc')
                ->select()
                ->toArray();
                
            // 准备Excel数据
            $data = [];
            foreach ($list as $item) {
                $data[] = [
                    '商家ID' => $item['merchant_id'],
                    '商家名称' => $item['merchant']['merchant_name'] ?? '',
                    '充值金额' => $item['recharge_amount'],
                    '充值方式' => $this->getRechargeType($item['recharge_type']),
                    '转账流水号' => $item['transfer_no'],
                    '状态' => $this->getStatus($item['status']),
                    '审核人' => $item['admin']['username'] ?? '',
                    '备注' => $item['remark'],
                    '创建时间' => $item['create_time'],
                    '更新时间' => $item['update_time']
                ];
            }
            
            // 导出Excel
            return excel_export('商家充值记录', $data);
        } catch (\Exception $e) {
            Log::error('导出充值记录失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取充值方式文本
     */
    protected function getRechargeType($type)
    {
        $types = [
            1 => '微信',
            2 => '支付宝',
            3 => '对公转账'
        ];
        return $types[$type] ?? '未知';
    }
    
    /**
     * 获取状态文本
     */
    protected function getStatus($status)
    {
        $statuses = [
            0 => '未支付',
            1 => '已支付',
            2 => '已充值',
            3 => '已取消'
        ];
        return $statuses[$status] ?? '未知';
    }
} 